package com.yingda.electronicscaleadvices.utils;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.yingda.electronicscaleadvices.MyAPP;
import com.yingda.electronicscaleadvices.bean.UpdateAppBean;
import com.yingda.electronicscaleadvices.eventbus.EventBus;
import com.yingda.electronicscaleadvices.net.Common;


import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * author: qzx
 * Date: 2020/3/19 16:58
 * <p>
 * notes：引入的Context要是ActivityCompat的Context,因为tipDialog需要getSupportFragmentManager()
 */
public class CheckVersionUtil {
    private static final int NEET_SERVER = 3;
    private MyHandler myHandler = new MyHandler();
    ;
    private static final int Update_App_Dialog = 0;
    private static final int Update_Check_Failed = 1;
    private static final int Is_New_Version = 2;

    private static final int Update_Check_No_Sucess = 3;

    private Activity context;
    public static final String TAG = "CheckVersionUtil";


    private CheckVersionUtil() {
    }

    private static CheckVersionUtil instance = new CheckVersionUtil();

    public static CheckVersionUtil getInstance() {
        synchronized (CheckVersionUtil.class) {
            return instance;
        }
    }

    public void requestCheckVersion(Activity context) {
        Log.i(TAG, "requestCheckVersion: 我多次被调用");
        this.context = context;
        try {
            //获取版本升级的url
            String url = Common.APPUP_DATE;
            JSONObject jsonObject = new JSONObject();
            //app类型:1-扫脸绑定;2-称重;3-芯片机;4-壁挂式消费机;5-卧式消费机 7-商米D2设备
            jsonObject.put("type", "7");
            String encrypt = AESEncryptUtils.encrypt(jsonObject.toString(), Constants.DECRYPT_KEY);
            OkHttp3_0Utils.getInstance().asyncBodyEncryptStringOkHttp(url, encrypt, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    QZXTools.logE("检测更新版本失败 " + e, null);
                    Message message = Message.obtain();
                    message.what = Update_Check_Failed;
                    message.obj = "检测更新版本失败";
                    myHandler.sendMessage(message);
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()) {
                        String resultJson = response.body().string();
                        QZXTools.logE("resultJson=" + resultJson, null);
                        try {
                            JSONObject jsonObject = null;
                            jsonObject = new JSONObject(resultJson);
                            int code = jsonObject.optInt("code");
                            String msg = jsonObject.optString("message");
                            String version = jsonObject.optString("version");
                            String timestamp = jsonObject.optString("timestamp");

                            Message message = Message.obtain();
                            if (code == 200) {
                                String realData = jsonObject.optString("data");
                                String decryData = AESEncryptUtils.decrypt(realData, Constants.DECRYPT_KEY);
                                QZXTools.logD(TAG, decryData);

                                com.alibaba.fastjson.JSONObject jsonObjectReal = new com.alibaba.fastjson.JSONObject();

                                jsonObjectReal.put("version", version);
                                jsonObjectReal.put("code", code);
                                jsonObjectReal.put("message", msg);
                                jsonObjectReal.put("data", JSON.parseObject(decryData));
                                jsonObjectReal.put("timestamp", timestamp);
                                String realContent = jsonObjectReal.toString();
                                QZXTools.logD(TAG, realContent);
                                UpdateAppBean updateAppBean = JSON.parseObject(realContent, UpdateAppBean.class);

                                UpdateAppBean.DataDTO updateAppBeanData = updateAppBean.getData();
                                QZXTools.logD(TAG, "最新版本=" + updateAppBeanData.getVersionCode());
                                message.what = Update_App_Dialog;
                                message.obj = updateAppBeanData;

                            } else {
                                //调用接口报错了
                                message.what = Update_Check_No_Sucess;
                                message.obj = msg;

                            }
                            myHandler.sendMessage(message);
                        } catch (Exception e) {
                            e.fillInStackTrace();
                            myHandler.sendEmptyMessage(Update_Check_Failed);
                        }

                    } else {
                        QZXTools.logE("检测版本应该是404", null);
                        Message message = Message.obtain();
                        message.what = Update_Check_Failed;
                        message.obj = "检测版本应该是404";
                        myHandler.sendMessage(message);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    public class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case Update_App_Dialog:
                    UpdateAppBean.DataDTO updateAppBeanData = (UpdateAppBean.DataDTO) msg.obj;
                    if (updateAppBeanData != null) {
                        Integer newCode = updateAppBeanData.getVersionCode();
                        int currentCode = QZXTools.getVersionCode(context);

                        if (currentCode < newCode) {
                            //开始升级
                            startUpApp(updateAppBeanData);

                        } else {
                            Log.i(TAG, "onResponse: 获取版本更新");
                            myHandler.sendEmptyMessage(Is_New_Version);
                        }

                    } else {
                        myHandler.sendEmptyMessage(Update_Check_Failed);
                    }

                    break;
                case Update_Check_Failed:
                    Toast.makeText(MyAPP.getInstance(), "检测更新失败，请重试！", Toast.LENGTH_SHORT).show();
                    break;

                case Update_Check_No_Sucess:
                    String info = (String) msg.obj;
                    Toast.makeText(MyAPP.getInstance(), info, Toast.LENGTH_SHORT).show();
                    break;
                case Is_New_Version:
                    //Log.i(TAG, ": Is_New_Version"+Is_New_Version);
                    Toast.makeText(MyAPP.getInstance(), "已是最新版本", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    }

    private void startUpApp(UpdateAppBean.DataDTO updateAppBeanData) {
        //有新版本
    /*    Intent intent = new Intent(context, UpdateAppActivity.class);
        intent.putExtra("apkUrl", updateAppBeanData.getApkUrl());
        intent.putExtra("versionName", updateAppBeanData.getVersionName());
        intent.putExtra("message", updateAppBeanData.getMessage());
        context.startActivity(intent);*/
        EventBus.getDefault().post(updateAppBeanData,Constants.VERSION_SHOW_UPDATE);



    }


}
